﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Rhino.Mocks;
using NSsh.Server.TransportLayer;
using NSsh.Common.Packets;
using NSsh.Common.Utility;
using System.IO;
using NSsh.Common;
using NSsh.Server.Configuration;
using Rhino.Mocks.Interfaces;

namespace NSsh.Server.Tests
{
    [TestFixture]
    public class SshSessionFixture
    {
        MockRepository _mockRepository;
        ITransportLayerManager _transportManager;
        ISshService _service;
        Stream _stream;
        IEventRaiser _idleTimeOutRaiser;

        [SetUp]
        public void Setup()
        {
            _mockRepository = new MockRepository();
            _transportManager = _mockRepository.CreateMock<ITransportLayerManager>();
            _service = _mockRepository.CreateMock<ISshService>();
            _stream = _mockRepository.CreateMock<Stream>();

            Dependency.Clear();
            Dependency.RegisterInstance<ITransportLayerManager>("ITransportLayerManager", _transportManager);
            Dependency.RegisterInstance<ISshService>("ISshService", _service);
        }

        [Test]
        public void ShouldDisconnectOnIdleTimeout()
        {
            using (_mockRepository.Record())
            {
                _transportManager.OnIdleTimeout += null;
                _idleTimeOutRaiser = LastCall.IgnoreArguments().GetEventRaiser();

                _transportManager.StartIdleTimeout(Dependency.Resolve<NSshServiceConfiguration>().IdleTimeout);
                _transportManager.Process(_stream);
                LastCall.Do(new MethodInvoker<Stream>(delegate
                    {
                        _idleTimeOutRaiser.Raise(_transportManager, EventArgs.Empty);
                    }));

                _transportManager.Disconnect(DisconnectReason.ByApplication);

                _service.DeregisterSession(null);
                LastCall.IgnoreArguments();

                _stream.Close();
            }

            using (_mockRepository.Playback())
            {
                SshSession session = new SshSession();
                session.SocketStream = _stream;
                session.Process();
            }
        }
    }
}
